package com.dfbz.controller.user;

import com.dfbz.common.Constr;
import com.dfbz.controller.BaseController;
import com.dfbz.model.User;
import com.dfbz.model.UserFocus;
import com.dfbz.service.DeptService;
import com.dfbz.service.UserService;
import com.dfbz.service.impl.DeptServiceImpl;
import com.dfbz.service.impl.UserServiceImpl;
import com.dfbz.utils.PageUtil;
import com.dfbz.utils.StrUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

@WebServlet("/user/*")
public class UserController extends BaseController {
    private UserService userService = new UserServiceImpl();
    private DeptService deptService=new DeptServiceImpl();

    public void look(HttpServletRequest req, HttpServletResponse resp){
        try {
            String id = req.getParameter("userId");
            Map<String,Object> map=userService.getUserInfo(id);
            req.setAttribute("userInfo",map);
            req.setAttribute("deptList",deptService.getAll());
            req.getRequestDispatcher("/assets/html/user_look.jsp").forward(req,resp);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void getUsers(HttpServletRequest req, HttpServletResponse resp){
        try {
            String page = req.getParameter("page");
            String name = req.getParameter("searchName");
            int currentPage=1;
            if (null!=page){
                currentPage=Integer.parseInt(page);
            }
            //从会话拿到当前登录的账户信息
            Map baseInfo=(Map) req.getSession().getAttribute("userBaseInfo");
            String userId = baseInfo.get("user_id").toString();

            List<Map<String, Object>> userList = userService.getUserList(userId,currentPage,name);
            req.setAttribute("userList",userList);
            long totalCount = userService.getUserCount(name);
            long totalPage = PageUtil.getTotalPage(totalCount);
            long startPage = PageUtil.getStartPage(currentPage);
            long endPage = PageUtil.getEndPage(currentPage, totalCount);
            req.setAttribute("currentPage",currentPage);
            req.setAttribute("searchName",name);
            req.setAttribute("totalCount",totalCount);
            req.setAttribute("totalPage",totalPage);
            req.setAttribute("pageCount",Constr.PAGE_COUNT);
            req.setAttribute("startPage",startPage);
            req.setAttribute("endPage",endPage);

            req.getRequestDispatcher("/assets/html/user.jsp").forward(req,resp);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void followUser(HttpServletRequest req, HttpServletResponse resp){
        try {
            String data;
            //关注的id
            String ufId = req.getParameter("ufId");
            //当前登录id
            String userId = getUserId(req);
            if (userId.equals(ufId)){
                data="不能关注自己";
            }else {
                //检查有没有重复关注
                UserFocus focus=userService.getFollowUser(userId,ufId);
                if (null!=focus){
                    //说明你之前关注过了，不能重复关注
                    data="你已关注";
                }else {
                    boolean b = userService.followUser(userId, ufId);
                    if (b){
                        data="1";
                    }else {
                        data="网络不佳，关注失败";
                    }
                }
            }
            resp.getWriter().write(data);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void unfollowUser(HttpServletRequest req, HttpServletResponse resp){
        try {
            String data;
            //关注的id
            String ufId = req.getParameter("ufId");
            //当前登录id
            String userId = getUserId(req);
            UserFocus focus=userService.getFollowUser(userId,ufId);
            if (null!=focus){
                boolean b = userService.unFollowUser(focus.getId());
                if (b){
                    data="1";
                }else {
                    data="取消关注失败";
                }
            }else {
                data="操作频繁，请稍候再试";
            }
            resp.getWriter().write(data);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public void uploadFile(HttpServletRequest req, HttpServletResponse resp){
        try {
            String fileName= StrUtil.getUUID() +Constr.IMG_SUFFIX;//用UUID生成唯一的编号
            InputStream is=null;
            FileOutputStream fos=null;
            try {
                ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
                List<FileItem> items = upload.parseRequest(req);
                if (!items.isEmpty()){
                    FileItem file = items.get(0);
                    String name = file.getName();
                    if (!name.contains("jpg")){
                        resp.getWriter().write(req.getContextPath()+Constr.DEFAULT_PATH);
                        return;
                    }
                    is = file.getInputStream();
                    fos = new FileOutputStream(Constr.FILE_PATH+fileName);
                    byte[] bytes = new byte[4 * 1024];
                    int len;
                    while (-1!=(len=is.read(bytes))){
                        fos.write(bytes,0,len);
                    }
                }
            } catch (FileUploadException | IOException e) {
                e.printStackTrace();
            }finally {
                if (null!=fos){
                    fos.close();
                }
                if (null!=is){
                    is.close();
                }
            }
            //更新路径到数据库 还要更新会话作用域的数据
            String userId = getUserId(req);
            userService.uploadImg(userId,Constr.IN_PATH+fileName);
            Map<String, Object> map = userService.findUserBaseInfo(getUserName(req));
            req.getSession().setAttribute("userBaseInfo", map);
            resp.getWriter().write(Constr.IN_PATH+fileName);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}